package com.siderakis.orgunit.client.ui;

import com.google.gwt.cell.client.AbstractEditableCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiRenderer;
import com.siderakis.orgunit.client.domain.OrgUnit;

public class AccessToggleCell extends AbstractEditableCell<OrgUnit, Boolean> {
  interface MyUiRenderer extends UiRenderer {
    void render(SafeHtmlBuilder sb, String name, String desc);

    void onBrowserEvent(AccessToggleCell o, NativeEvent e, Element p, OrgUnit n);

    AStyle getOnOffStyle();

    SpanElement getTurnOffSpan(Element parent);

    SpanElement getTurnOnSpan(Element parent);

  }

  public interface AStyle extends CssResource {
    String onUp();

    String onDown();

    String offUp();

    String offDown();
  }

  @Override
  public void onBrowserEvent(Context context, Element parent, OrgUnit value, NativeEvent event,
      ValueUpdater<OrgUnit> updater) {
    renderer.onBrowserEvent(this, event, parent, value);
  }

  private static MyUiRenderer renderer = GWT.create(MyUiRenderer.class);

  public AccessToggleCell() {
    super("click");
  }

  @UiHandler("turnOnSpan")
  void onNameGotPressed(ClickEvent event, Element parent, OrgUnit name) {
    name.setOn(true);
    renderer.getTurnOnSpan(parent).replaceClassName(renderer.getOnOffStyle().onUp(),
        renderer.getOnOffStyle().onDown());
    renderer.getTurnOffSpan(parent).replaceClassName(renderer.getOnOffStyle().offDown(),
        renderer.getOnOffStyle().offUp());

    // name.setInherits(on);
  }

  @UiHandler("turnOffSpan")
  void onNameGostPressed(ClickEvent event, Element parent, OrgUnit name) {
    name.setOn(false);
    renderer.getTurnOnSpan(parent).replaceClassName(renderer.getOnOffStyle().onDown(),
        renderer.getOnOffStyle().onUp());
    renderer.getTurnOffSpan(parent).replaceClassName(renderer.getOnOffStyle().offUp(),
        renderer.getOnOffStyle().offDown());

  }

  @Override
  public void render(Context context, OrgUnit value, SafeHtmlBuilder builder) {
    renderer.render(builder, value.getName(), value.getDescription());
  }

  @Override
  public boolean isEditing(com.google.gwt.cell.client.Cell.Context context, Element parent,
      OrgUnit value) {
    return false;
  }

}
